<template>
  <div class="businessAndCharges h100">
    <div class="PageContent">
        <el-col :span="4" class="left-tree">
          <el-tree :data="treeData" ref="businesstree"
                   :props="defaultProps"
                   node-key="id"
                   default-expand-all
                   check-strictly
                   highlight-current
                   @node-click="handleClick"
          ></el-tree>
        </el-col>
        <el-col :span="20"  class="right-tree">
          <el-row style="text-align: left;line-height: 5em;">
            <el-button type="primary"   v-if="btnRight.btnBusinessAndChargesAdd" @click="add()">追加物品服务关联</el-button>
            <el-button type="danger"   v-if="btnRight.btnBusinessAndChargesDelete" @click="remove()">删除关联</el-button>
          </el-row>
          <el-table
            ref="businessTable"
            :data="tableData" :header-cell-style="{background:'rgb(246,247,251)',color:'#606266'}"
            stripe
            border
            @row-click="handleRowClick"
            style="width: 100%;height: calc(100% - 80px);overflow-y: scroll">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <!--<el-table-column-->
              <!--property="itemCode"-->
              <!--label="项目编码"-->
              <!--align = 'center'-->
              <!--width="250">-->
            <!--</el-table-column>-->
            <el-table-column
              property="itemName"
              label="项目名称"
              align = 'center'>
            </el-table-column>
            <el-table-column
              property="itemPrice"
              label="价格"
              align = 'center'
              width="100">
            </el-table-column>
            <el-table-column
              property="itemNumber"
              align = 'center'
              label="数量"
              width="100">
            </el-table-column>
            <el-table-column
              property="itemUnit"
              align = 'center'
              label="单位"
              width="100">
            </el-table-column>
            <el-table-column
              property="asGoods"
              align = 'center'
              label="服务/物品"
              width="150">
              <template slot-scope="{row,$index}">
                <span v-if="row.asGoods==0">服务</span>
                <span v-else-if="row.asGoods==1">物品</span>
              </template>
            </el-table-column>
            <el-table-column
              property="asPackage"
              align = 'center'
              label="是否物品包"
              width="150">
              <template slot-scope="{row,$index}">
                <span v-if="row.asPackage==0">普通服务物品</span>
                <span v-else-if="row.asPackage==1">物品包</span>
              </template>
            </el-table-column>
            <el-table-column
              property="asFixPrice"
              align = 'center'
              label="固定价格"
              width="150">
              <template slot-scope="{row,$index}">
                <span v-if="row.asFixPrice==1">固定价格</span>
                <span v-else-if="row.asFixPrice==0">议价</span>
              </template>
            </el-table-column>
            <el-table-column
              property="itemDescribe"
              align = 'center'
              label="状态"
              width="150">
              <template slot-scope="{row,$index}">
                <span v-if="row.disableState==0">有效，可销售</span>
                <span v-else-if="row.disableState==1">无效，不可销售</span>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
    </div>
    <el-dialog title="物品服务" :visible.sync="DialogGoodsService" v-dialogDrag width="800px"  border>
      <el-row style="line-height: 40px;margin-bottom: 10px;">
        <label>根据项目名称或单价检索：<el-input v-model="search" style="width: 300px;"></el-input></label>
      </el-row>
      <el-row style=" height:500px;overflow-y: scroll">
        <el-table
          ref="bussinessAndChargeTable"
          :data="tables"
          :header-cell-style="{background:'rgb(246,247,251)',color:'#606266'}"
          stripe
          tooltip-effect="dark"
          style="width: 100%"
          @row-click="handleRowClickDialog"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            align = 'center'
            width="100">
          </el-table-column>
          <el-table-column align = 'center'  prop="itemName"  label="项目名称" width="200">
          </el-table-column>
          <el-table-column
            prop="itemPrice"
            align = 'right'
            label="单价"
            width="100">
          </el-table-column>
          <el-table-column
            prop="itemNumber"
            align = 'right'
            label="数量"
            width="100">
          </el-table-column>
          <el-table-column
            prop="itemUnit"
            align = 'center'
            label="单位"
            width="100">
          </el-table-column>
          <el-table-column
            prop="asGoods"
            align = 'center'
            label="是否物品"
            width="100">
            <template slot-scope="{row,$index}">
              <span v-if="row.asGoods==0">服务</span>
              <span v-else-if="row.asGoods==1">物品</span>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button type="primary"  v-if="btnRight.btnBusinessAndChargesSave"  @click="Save()" :disabled="saveFlag">保 存</el-button>
        <el-button type="primary" plain  v-if="btnRight.btnBusinessAndChargesCancel" @click="DialogGoodsService = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as API from '@/api/systemApplication'
  import {treeTransformate} from "../../utils/treeTransformate";

  export default {
    name: "businessAndCharges",
    data(){
      return{
        treeData: [{
          id: 0,
          label: '业务模块',
          children: [
            {
              id: 1,
              label: '接运用物品服务',
              code:"use_in_transport_task"
            },
            {
              id: 2,
              label: '冷藏用物品服务',
              code:"use_in_cold_storage"
            },
            {
              id: 3,
              label: '礼厅用物品服务',
              code:"use_in_mourn_ceremony"
            },
            {
              id: 4,
              label: '火化用物品服务',
              code:"use_in_cremation"
            },
            {
              id: 5,
              label: '整容服务',
              code:"type_of_face_lift"
            },
            {
              id: 6,
              label: '丧葬用品服务',
              code:"type_of_funeral_supplies"
            },
            {
              id: 7,
              label: '接运信息服务',
              code:"use_in_rec_info"
            }
          ]
        }],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        tableData: [],
        goodsServiceList:[],//所有的物品服务包
        currentRow: null,
        tableSelection:[],
        multipleSelection:[],
        saveFlag:false, //保存标志
        onpresscTime:0,  //  阻止短时间内连续点击
        DialogGoodsService:false,//项目分类维护对话框
        search:"",    //模糊查询
        saveTypeData:{       //保存服务物品类型基本信息
          "id": "",
          "parentId": "",
          "typeCode": "",
          "typeName": "",
          "typeDescribe": "",
          "sort": "",
          "remark": "",
          "version": 0
        }, btnRight: {
          btnBusinessAndChargesAdd: true, //追加物品服务关联
          btnBusinessAndChargesDelete: true,//删除关联
          btnBusinessAndChargesSave: true,//保存关联
          btnBusinessAndChargesCancel: true,//取消关联
        }
      }
    },
    computed: {
      // 模糊搜索
      tables () {
        const search = this.search
        if (search) {
          // filter() 方法创建一个新的数组，新数组中的元素是通过检查指定数组中符合条件的所有元素。
          return this.goodsServiceList.filter(data => {
            // some() 方法用于检测数组中的元素是否满足指定条件;
            {
              return Object.keys(data).some(key => {
                // indexOf() 返回某个指定的字符在某个字符串中首次出现的位置，如果没有找到就返回-1；
                // 该方法对大小写敏感！所以之前需要toLowerCase()方法将所有查询到内容变为小写。
                if (key=="itemName" ||key =="itemPrice"){
                  return String(data[key]).indexOf(search) > -1
                }
              })
            }

          })
        }
        return this.goodsServiceList
      }
    },mounted() {
      //获得菜单按钮
      this.btnRight = this.$route.meta.buttons;
      //遍历属性赋值将true与false字符串转换成布尔型的值
      for (let key of Object.keys(this.btnRight)) {
        this.btnRight[key]=(this.btnRight[key]|| this.btnRight[key]=="true")?true:false;
      }
    },
    methods: {
      //table中类型添加
      add(){
        let data = this.$refs.businesstree.getCheckedNodes()
        if (data && data.length){
          API['loadGoodsServiceList']().then(response=>{
            const { data }=response;
            if (!data) {
              this.$message('数据读取失败')
              return
            }
            this.goodsServiceList = data
            if (this.goodsServiceList.length){
              this.DialogGoodsService=true
            }
          }).catch(error => {
            this.$message(error)
          })
        } else{
          this.$message("请选择业务模块")
        }
      },
      //table中服务物品类型删除
      remove(){
        let data = this.$refs.businessTable.selection
        if (data.length==0) {
          this.$message("未选中服务物品")
          return
        }
        this.$confirm('删除信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let postData=[]
          data.forEach(item=>{
            postData.push({
              "id": item.id,
              "version": item.version
            })
          })
          API['deleteServiceBusinessDataWithId'](postData).then(response=>{
            const { message }=response;
            this.$message(message)
            let data = this.$refs.businesstree.getCheckedNodes()
            this.loadServiceBusinessDataListWithCodeData(data[0].code)
          }).catch(error => {
            this.$message(error)
          })
        }).catch(() => {
          //几点取消的提示
        });

      },
      //tree单选
      handleClick(data,checked, node){
        if(checked && data.label!="业务模块"){
          this.$refs.businesstree.setCheckedNodes([data]);
          this.loadServiceBusinessDataListWithCodeData(data.code)
        }
      },
      //点击行触发，选中或不选中复选框
      handleRowClick(row, column, event) {
        this.$refs.businessTable.toggleRowSelection(row);
        let data = this.$refs.businessTable.selection
        this.tableSelection = data
      },
      handleRowClickDialog(row, column, event) {
        this.$refs.bussinessAndChargeTable.toggleRowSelection(row);
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      //****数据方法开始****//
      loadServiceBusinessDataListWithCodeData(code){
        let postData={
          "businessType": code
        }
        API['loadServiceBusinessDataListWithCode'](postData).then(response=>{
          const { data }=response;
          if (!data) {
            this.$message('数据读取失败')
            return
          }
          this.tableData = data

        }).catch(error => {
          this.$message(error)
        })
      },

      //服务物品保存
      Save(){
        if ((Date.now() - this.onpresscTime) > 2000) {
          this.onpresscTime = Date.now()
          console.log(Date.now())
        }else{
          return
        }
        let data = this.$refs.businesstree.getCheckedNodes()
        let selectData = this.multipleSelection
        if (data && data.length){
          if (selectData && selectData.length){
            let postData = []
            selectData.forEach(item=>{
              postData.push( {
                "businessType": data[0].code,
                "serviceItemId": item.id
              })
            })
            this.saveFlag = true
            console.log(postData)
            API['saveServiceBusinessData'](postData).then(response=>{
              const { message }=response;
              this.$message(message)
              let data = this.$refs.businesstree.getCheckedNodes()
              this.loadServiceBusinessDataListWithCodeData(data[0].code)
              this.DialogGoodsService = false
              this.saveFlag = false
            }).catch(error => {
              this.$message(error)
              this.saveFlag = false
            })
          } else{
            this.$message("未选中服务物品")
          }
        } else{
          this.$message("加载信息出错")
        }

      },
    }
  }
</script>
<style>

</style>
<style scoped>

  .list{
    display: flex;flex-wrap: wrap;
    margin:5px 0px;
    justify-content: space-between;
    padding-left: 120px;
    text-align: left;
  }
  .list .item {
    font-size: 14px;
    font-weight: 400;
    line-height: 30px;
    /*width: 150px;*/
    height:30px;
    background-color: #efefef;
    padding:0 5px;
    border-radius:5px;
    overflow: hidden;
    margin-bottom: 10px;
    text-align: center;
  }
  .list .title{
    margin-right: 10px;
    float: left;
  }
  .list .delete{
    line-height: 30px;
    margin-left: 10px;
    color:red;
    float: right;
    cursor: pointer;
  }
  .wrapper{
    display: flex;
    flex-wrap: wrap;
    margin:5px 0px;
    justify-content: space-between;
    height:500px;
    overflow-y: auto;
  }
  .box-card {
    flex:0 0 150px;
    display: inline-block;
    box-shadow:  0 2px 12px 0 rgba(0,0,0,.1);;
    margin-bottom: 30px;
    margin-right: 10px;
  }
  .box-card .item {
    font-size: 16px;
    font-weight: 400;
    line-height: 30px;
    width: 100%;
    height: 90px;
    text-align: center;
    padding: 0 1em;
    border-radius:5px;
    overflow: hidden;
  }
  .item:hover{
    cursor: pointer;
  }
  .item:last-child{
    margin-bottom: 0px;
  }
  .item.select{
    background-color: lightgreen;
  }
  .item h2{
    height: 30px;
    overflow: hidden;
  }
</style>
